package com.example.springboot_demo.demos.web.websocket_work.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@EnableScheduling
public class MessageRankService {
    private static final String MESSAGE_RANK_KEY  = "chat:message_rank";

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //增加用户消息计数
    public void incrementMessageCount(String userId){
        redisTemplate.opsForZSet().incrementScore(MESSAGE_RANK_KEY,userId,1);
    }

    // 获取Top10用户
    public Set<ZSetOperations.TypedTuple<String>> getTopUsers() {
        return redisTemplate.opsForZSet()
                .reverseRangeWithScores(MESSAGE_RANK_KEY, 0, 9);
    }

    @Scheduled(cron = "0 */3 * * * *")
    public void cleanOldRanks() {
        long now = System.currentTimeMillis();
        redisTemplate.opsForZSet().removeRangeByScore(
                MESSAGE_RANK_KEY, 0, now - 7 * 86400_000
        );
    }

    //消息频率限制
    public boolean checkRateLimit(String userId) {
        String key = "chat:rate_limit:" + userId;
        Long count = redisTemplate.opsForValue().increment(key);
        redisTemplate.expire(key, 1, TimeUnit.MINUTES);
        return count != null && count <= 3; // 每分钟30条
    }
}
